/*
 * @Author: your name
 * @Date: 2022-01-28 10:35:57
 * @LastEditTime: 2022-01-29 10:35:14
 * @LastEditors: LAPTOP-L472H14P
 * @Description: In User Settings Edit
 * @FilePath: \react_front_engineer\src\NodeJs\login&registy\router\user.js
 */
const express = require('express')
const router = express.Router()
const db = require('../dbConnect/mysql')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken') // 生成token字符串
const jwtSecretKey = 'hand'
// 注册接口
router.post('/register', (req, res) => {
  const registerSql = `select username from user_info where username="${req.body.username}"`
  db.query(registerSql, (err, result) => {
    if (result.length === 0) {
      const psd = bcrypt.hashSync(req.body.password, 10)
      const createSql = `INSERT INTO user_info (username,password) VALUES("${req.body.username}", "${psd}")`
      db.query(createSql, (err, result) => {
        if (result.affectedRows === 1) {
        //   const tokenStr = jwt.sign(req.body.username, jwtSecretKey, {
        //     expiresIn: '50s', // token 有效期为 10 个小时
        //   })
          const token = jwt.sign({ username: req.body.username, age: 30 }, jwtSecretKey, {
            expiresIn: '30h',
          })
          res.send({
            status: 201,
            message: '注册成功',
            token,
          })
        }
      })
    } else {
      res.send({
        status: 201,
        message: '用户名已存在',
        result: result,
      })
    }
  })
})
// 登录接口
router.post('/login', (req, res) => {
  const querySql = `SELECT * from user_info WHERE username="${req.body.username}"`
  db.query(querySql, (err, result) => {
    if (err) return err
    if (result.length === 0) {
      res.send({
        message: '未查到当前用户，请前往注册',
      })
    } else {
      const compareResult = bcrypt.compareSync(
        req.body.password,
        result[0].password,
      )
      if (result[0].username === req.body.username && compareResult) {
        const token = jwt.sign({ username: req.body.username, age: 30 }, jwtSecretKey, {
            expiresIn: '30h',
          })
        res.send({
          message: '登录成功',
          token
        })
      } else {
        res.send({
          message: '用户名或密码错误,请重新输入',
        })
      }
    }
  })
})

module.exports = router
